package city.spring.modules.system.controller;

import city.spring.modules.system.entity.DataDictionaryValueEntity;
import city.spring.modules.system.service.DataDictionaryValueService;
import city.spring.utils.MyBatisUtils;
import com.baomidou.mybatisplus.core.toolkit.support.SFunction;
import com.baomidou.mybatisplus.extension.api.ApiController;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.commons.lang.StringUtils;
import org.springframework.data.domain.Pageable;
import org.springframework.data.web.PageableDefault;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

/**
 * 数据字典值信息 控制器
 *
 * @author HouKunLin
 * @date 2020/3/26 0026 23:40
 */
@RestController
@RequestMapping("/dataDictionary/{dictionaryId}/value")
public class DataDictionaryValueController extends ApiController {
    /**
     * <strong>数据字典值信息</strong> Service
     */
    private final DataDictionaryValueService dataDictionaryValueService;
    /**
     * 实体类（数据字典值信息）可排序字段
     */
    private final List<SFunction<DataDictionaryValueEntity, ?>> entityOrderFields;

    public DataDictionaryValueController(DataDictionaryValueService dataDictionaryValueService) {
        this.dataDictionaryValueService = dataDictionaryValueService;
        this.entityOrderFields = new ArrayList<>();
        this.entityOrderFields.add(DataDictionaryValueEntity::getId);
        this.entityOrderFields.add(DataDictionaryValueEntity::getDictionaryId);
        this.entityOrderFields.add(DataDictionaryValueEntity::getLabel);
        this.entityOrderFields.add(DataDictionaryValueEntity::getValue);
        this.entityOrderFields.add(DataDictionaryValueEntity::getEnabled);
        this.entityOrderFields.add(DataDictionaryValueEntity::getSorted);
        this.entityOrderFields.add(DataDictionaryValueEntity::getGmtCreate);
        this.entityOrderFields.add(DataDictionaryValueEntity::getGmtModified);
    }

    /**
     * 获取全部的 <strong>数据字典值信息</strong> 列表
     */
    @PreAuthorize("hasAnyRole('ADMIN', 'DICTIONARY.VALUE') or hasAnyAuthority('dictionary.value.list')")
    @GetMapping("all")
    public Object listAll(@PageableDefault Pageable pageable, DataDictionaryValueEntity entity, @PathVariable String dictionaryId) {
        LambdaQueryChainWrapper<DataDictionaryValueEntity> lambdaQuery = buildLambdaQuery(entity);
        MyBatisUtils.lambdaQueryAddOrder(lambdaQuery, pageable, entityOrderFields);
        lambdaQuery.eq(DataDictionaryValueEntity::getDictionaryId, dictionaryId);
        return success(lambdaQuery.list());
    }

    /**
     * 分页获取 <strong>数据字典值信息</strong> 列表
     *
     * @param pageable 分页参数信息
     */
    @PreAuthorize("hasAnyRole('ADMIN', 'DICTIONARY.VALUE') or hasAnyAuthority('dictionary.value.list')")
    @GetMapping
    public Object list(@PageableDefault Pageable pageable, DataDictionaryValueEntity entity, @PathVariable String dictionaryId) {
        LambdaQueryChainWrapper<DataDictionaryValueEntity> lambdaQuery = buildLambdaQuery(entity);
        MyBatisUtils.lambdaQueryAddOrder(lambdaQuery, pageable, entityOrderFields);
        lambdaQuery.eq(DataDictionaryValueEntity::getDictionaryId, dictionaryId);
        Page<DataDictionaryValueEntity> page = lambdaQuery.page(MyBatisUtils.toPage(pageable, false));
        return success(page);
    }

    /**
     * 获取一个 <strong>数据字典值信息</strong>
     *
     * @param id 主键ID
     */
    @PreAuthorize("hasAnyRole('ADMIN', 'DICTIONARY.VALUE') or hasAnyAuthority('dictionary.value.info')")
    @GetMapping("{id}")
    public Object info(@PathVariable String id) {
        return success(dataDictionaryValueService.getById(id));
    }

    /**
     * 添加一个 <strong>数据字典值信息</strong>
     *
     * @param entity 新增的信息
     */
    @PreAuthorize("hasAnyRole('ADMIN', 'DICTIONARY.VALUE') or hasAnyAuthority('dictionary.value.add')")
    @PostMapping
    public Object add(@RequestBody DataDictionaryValueEntity entity, @PathVariable String dictionaryId) {
        entity.setDictionaryId(dictionaryId);
        dataDictionaryValueService.saveDataDictionaryValue(entity);
        HttpHeaders headers = new HttpHeaders();
        headers.add(HttpHeaders.LOCATION, entity.getId());
        return new ResponseEntity<>(headers, HttpStatus.CREATED);
    }

    /**
     * 修改一个 <strong>数据字典值信息</strong>
     *
     * @param id     主键ID
     * @param entity 修改后的信息
     */
    @PreAuthorize("hasAnyRole('ADMIN', 'DICTIONARY.VALUE') or hasAnyAuthority('dictionary.value.update')")
    @PutMapping("{id}")
    public Object update(@PathVariable String id, @RequestBody DataDictionaryValueEntity entity, @PathVariable String dictionaryId) {
        entity.setId(id);
        entity.setDictionaryId(dictionaryId);
        dataDictionaryValueService.updateDataDictionaryValue(entity);
        return new ResponseEntity<>(HttpStatus.OK);
    }

    /**
     * 更新字典值的启用状态
     *
     * @param id      字典值ID
     * @param enabled 启用状态
     */
    @PreAuthorize("hasAnyRole('ADMIN', 'DICTIONARY.VALUE') or hasAnyAuthority('dictionary.value.enabled')")
    @PutMapping("{id}/enabled/{enabled}")
    public Object update(@PathVariable String id, @PathVariable Boolean enabled) {
        if (enabled != null) {
            dataDictionaryValueService.enabled(id, enabled);
        }
        return new ResponseEntity<>(HttpStatus.OK);
    }

    /**
     * 删除一个 <strong>数据字典值信息</strong>
     *
     * @param id 主键ID
     */
    @PreAuthorize("hasAnyRole('ADMIN', 'DICTIONARY.VALUE') or hasAnyAuthority('dictionary.value.delete')")
    @DeleteMapping("{id}")
    public Object delete(@PathVariable String id) {
        dataDictionaryValueService.deleteDataDictionaryValue(id);
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }

    /**
     * 删除多个 <strong>数据字典值信息</strong>
     *
     * @param ids 主键ID列表
     */
    @PreAuthorize("hasAnyRole('ADMIN', 'DICTIONARY.VALUE') or hasAnyAuthority('dictionary.value.delete')")
    @DeleteMapping
    public Object deleteIds(@RequestBody List<String> ids) {
        dataDictionaryValueService.deleteDataDictionaryValue(ids);
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }

    /**
     * 构建查询条件内容
     *
     * @param entity 实体对象： <strong>数据字典值信息</strong>
     * @return lambda query chain wrapper
     */
    private LambdaQueryChainWrapper<DataDictionaryValueEntity> buildLambdaQuery(DataDictionaryValueEntity entity) {
        LambdaQueryChainWrapper<DataDictionaryValueEntity> lambdaQuery = dataDictionaryValueService.lambdaQuery();
        lambdaQuery.eq(StringUtils.isNotBlank(entity.getId()), DataDictionaryValueEntity::getId, entity.getId());
        lambdaQuery.eq(StringUtils.isNotBlank(entity.getLabel()), DataDictionaryValueEntity::getLabel, entity.getLabel());
        lambdaQuery.eq(StringUtils.isNotBlank(entity.getValue()), DataDictionaryValueEntity::getValue, entity.getValue());
        lambdaQuery.eq(StringUtils.isNotBlank(entity.getRemarks()), DataDictionaryValueEntity::getRemarks, entity.getRemarks());
        lambdaQuery.eq(entity.getEnabled() != null, DataDictionaryValueEntity::getEnabled, entity.getEnabled());
        return lambdaQuery;
    }
}
